import { useDebounceEffect } from 'ahooks';
import { App, Button } from 'antd';
import React, { useCallback, useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import pluginService from '@/api/services/pluginService';
import { SetPoliciesReq } from '@/common';
import { AppStatusEnum, UserRoleEnum } from '@/common/app/constants';
import { SvgIcon } from '@/components/icon';
import MyModal from '@/components/MyModal';
import Back from '@/components/router/Back';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useConfirm } from '@/hooks/use-confirm';
import { useRequest2 } from '@/hooks/use-request';
import { t } from '@/locales/i18n';
import PublishComponent from '@/pages/app-orchestration/components/PublishComponent';
import { formatTime2YMDHMS } from '@/pages/chat/tools/time';
import { useRouter } from '@/router/hooks';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { PublishTypeEnum } from '@/types/app/type';
import { compareSnapshot } from '@/utils/workflow/utils';

import { AppContext, TabEnum } from '../../../context';
import { WorkflowContext } from '../context';

import RouteTab from './RouteTab';

function Header() {
  const { isPc } = useWindowWidth();
  const router = useRouter();
  const { message } = App.useApp();

  const { appId, appDetail, onSaveApp, currentTab, from } = useContextSelector(
    AppContext,
    (v) => v,
  );

  const {
    appName,
    tag,
    appLogo,
    appDescription,
    sceneImage,
    permissionConfig,
    setVariables,
    userRole,
    isPublishTemplate,
    appDetail: appDetailInfo,
  } = useOrchestrationStore();

  const isEditable = useMemo(() => {
    return userRole === UserRoleEnum.admin;
  }, [userRole]);

  const [isOpenBackConfirm, setIsOpenBackConfirm] = useState(false);

  const onOpenBackConfirm = () => {
    setIsOpenBackConfirm(true);
  };

  const onCloseBackConfirm = () => {
    setIsOpenBackConfirm(false);
  };

  const { flowData2StoreData, showHistoryModal, nodes, edges, past, future, setPast, checkList } =
    useContextSelector(WorkflowContext, (v) => v);

  const [isPublished, setIsPublished] = useState(false);
  useDebounceEffect(
    () => {
      const savedSnapshot =
        future.findLast((snapshot) => snapshot.isSaved) ||
        past.find((snapshot) => snapshot.isSaved);

      const val = compareSnapshot(
        {
          nodes: savedSnapshot?.nodes,
          edges: savedSnapshot?.edges,
          chatConfig: savedSnapshot?.chatConfig,
        },
        {
          nodes,
          edges,
          chatConfig: appDetail.chatConfig,
        },
      );
      setIsPublished(val);
    },
    [future, past, nodes, edges, appDetail.chatConfig],
    {
      wait: 500,
    },
  );

  const { runAsync: onClickSave, loading } = useRequest2(
    async ({
      isPublish,
      versionName = formatTime2YMDHMS(new Date()),
      permissionConfig,
      publishType,
    }: {
      isPublish?: boolean;
      versionName?: string;
      permissionConfig?: SetPoliciesReq['statements'];
      publishType?: PublishTypeEnum;
    }) => {
      const data = flowData2StoreData();
      // isPublish && datasetService.knowledgeBasePublish({ app_id: appId });
      if (data) {
        console.log('tag', tag);

        await onSaveApp({
          ...data,
          is_publish: isPublish,
          version_name: versionName,
          chat_config: appDetail.chatConfig,
          // @ts-ignore
          version: 'v2',
          configurations: [],
          permission_config: permissionConfig ?? [],
          app_name: appName,
          tag,
          app_logo: appLogo,
          app_description: appDescription,
          scene_image: sceneImage,
          isPublishTemplate,
          publishType,
        });
        // Mark the current snapshot as saved
        setPast((prevPast) =>
          prevPast.map((item, index) =>
            index === 0
              ? {
                  ...item,
                  isSaved: true,
                }
              : item,
          ),
        );
      }
    },
  );

  const { openConfirm, ConfirmModal } = useConfirm({
    content: t('confirm_public_plugin_inuse_tip_workflow', { count: 0 }),
    type: 'common',
    hideFooter: false,
    showClose: false,
    showCancel: true,
  });

  const onSave = useCallback(
    async (
      is_publish?: boolean,
      permissionConfig?: SetPoliciesReq['statements'],
      is_all_can_qa?: boolean,
      publishType?: PublishTypeEnum,
    ) => {
      const data = is_publish ? checkList?.isValid : true;

      if (data) {
        if (appDetailInfo?.review_status == AppStatusEnum.pending) {
          message.info('应用审核中，暂不支持重新发布');
          return;
        }

        if (
          appDetailInfo?.appType === PublishTypeEnum.plugin &&
          publishType === PublishTypeEnum.workflow
        ) {
          const res = await pluginService.getPluginUsedCount(appDetailInfo.app_id);
          const { count } = res;
          if (count > 0) {
            openConfirm(
              async () => {
                await onClickSave({
                  isPublish: is_publish,
                  versionName: formatTime2YMDHMS(new Date()),
                  permissionConfig,
                  publishType,
                });
                message.success(t('publish_success'));
              },
              undefined,
              t('confirm_public_plugin_inuse_tip_workflow', { count }),
            )();
            return;
          }
        }

        await onClickSave({
          isPublish: is_publish,
          versionName: formatTime2YMDHMS(new Date()),
          permissionConfig,
          publishType,
        });
        message.success(t('publish_success'));
      } else {
        message.warning(t('core.workflow.Check Failed'));
      }
    },
    [
      checkList?.isValid,
      appDetailInfo?.review_status,
      appDetailInfo?.appType,
      appDetailInfo.app_id,
      onClickSave,
      message,
      openConfirm,
    ],
  );

  const onPublish = useCallback(
    async (publish: boolean) => {
      const data = publish ? checkList?.isValid : true;
      console.log(publish, permissionConfig, checkList);
      if (data) {
        await onClickSave({
          isPublish: publish,
          versionName: formatTime2YMDHMS(new Date()),
        });
        message.success(t('saved_success'));
      } else {
        message.warning(t('core.workflow.Check Failed'));
      }
    },
    [checkList, permissionConfig, onClickSave, message],
  );

  const onBack = useCallback(async () => {
    try {
      localStorage.removeItem(`${appDetail.id}-past`);
      localStorage.removeItem(`${appDetail.id}-future`);
      setVariables({});

      if (appDetailInfo?.appType === PublishTypeEnum.plugin && from) {
        router.push(from);
        return;
      }

      if (currentTab === TabEnum.preview) {
        // 如果没有key参数，则跳转工作台
        const params = new URLSearchParams(window.location.search);
        if (!params.get('key')) {
          router.push('/worklayouts/');
          return;
        }
        router.push('/worklayouts/appReviewCenter/app-review');
      } else {
        router.push('/worklayouts/');
      }
    } catch (error) {
      console.error(error);
    }
  }, [appDetail.id, appDetailInfo?.appType, currentTab, from, router, setVariables]);

  // 使用useCallback包裹switchTab，避免每次渲染都创建新函数，修复useMemo依赖警告
  const switchTab = useCallback(
    (tab: string) => {
      const searchParams = new URLSearchParams(window.location.search);
      searchParams.set('currentTab', tab);

      const url = `/app/workflow?${searchParams.toString()}`;
      router.replace(url);
    },
    [router],
  );

  const Render = useMemo(() => {
    return (
      <div className="w-full">
        {!isPc && (
          <div className="justify-center pt-2">
            <RouteTab />
          </div>
        )}
        <div className="flex h-[60px] select-none flex-wrap items-center bg-white pl-2 pr-2 shadow-sm">
          {/* back */}
          {/* <LeftOutlined /> */}
          <Back
            onClick={isPublished || currentTab === TabEnum.preview ? onBack : onOpenBackConfirm}
            className="ml-2 mr-3"
          />

          <div className="flex gap-2 text-base">
            <div className="flex cursor-pointer items-center gap-3 text-gray-600">
              <AvatarDisplay
                src={appLogo}
                className="h-[32px] max-h-[32px] w-[32px] max-w-[32px]"
                size={32}
              />
              <span className="text-base font-font-weight-600 text-text-5">{appName}</span>
              {currentTab !== TabEnum.preview && (
                <div className="ml-1 flex items-center justify-center gap-1">
                  <SvgIcon size={16} icon={isPublished ? 'tz-SUCCESS' : 'tz-FAILURE'} />
                  <span className="text-sm text-text-3">
                    {' '}
                    {isPublished ? t('core.app.have_saved') : t('core.app.not_saved')}
                  </span>
                </div>
              )}
            </div>
          </div>

          {isPc && (
            <div
              className="absolute h-[60px]"
              style={{
                left: '50%',
                transform: 'translateX(-50%)',
              }}
            >
              <RouteTab />
            </div>
          )}

          {currentTab === TabEnum.appEdit && isEditable && (
            <div className="ml-auto flex gap-2">
              {!showHistoryModal && (
                <div className="mr-2 flex items-center gap-2">
                  <Button
                    loading={loading}
                    style={{
                      background: 'var(--fill-1)',
                      borderColor: 'var(--line-2)',
                    }}
                    onClick={() => {
                      onPublish(false);
                    }}
                  >
                    <span className="text-text-5">{t('core.workflow.Save to cloud')}</span>
                  </Button>
                  <PublishComponent
                    appId={appId}
                    onSave={onSave}
                    isWorkflow
                    onSwitchToKnowledgeTab={switchTab}
                  />
                </div>
              )}
            </div>
          )}
        </div>
        <ConfirmModal />
      </div>
    );
  }, [
    isPc,
    isPublished,
    currentTab,
    onBack,
    appLogo,
    appName,
    isEditable,
    showHistoryModal,
    loading,
    appId,
    onSave,
    switchTab,
    ConfirmModal,
    onPublish,
  ]);

  return (
    <>
      {Render}
      <MyModal
        isOpen={isOpenBackConfirm}
        onClose={onCloseBackConfirm}
        iconSrc="runError"
        title={t('common.Exit')}
        maxW="450px"
        minW="450px"
      >
        <div className="mt-4">
          <div>{t('workflow.exit_tips')}</div>
        </div>
        <div className="ml-auto mt-8 flex gap-3">
          <Button danger onClick={onBack}>
            {t('common.Exit Directly')}
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={async () => {
              await onClickSave({ isPublish: false });
              onCloseBackConfirm();
              onBack();
              message.success(t('saved_success'));
            }}
          >
            {t('common.Save_and_exit')}
          </Button>
        </div>
      </MyModal>
    </>
  );
}

export default React.memo(Header);
